var gzlx = '';
var dtsydd = '';
var lc = '';
var cxtime = '';
var wbry = '';
var lxdh = '';
var dtnbbm = '';
//传递故障电梯基本信息
function getGZInfo(gzid) {
	return "gzlx=" + gzlx +
		";cxsj=" + cxtime +
		";wymc=" + dtsydd +
		";dtnbbm=" + dtnbbm +
		";gzlc=" + lc +
		";wbry=" + wbry +
		";lxdh=" + lxdh;
}
$(function() {
	mui.init({
		pullRefresh: {
			container: refreshContainer, //待刷新区域标识，querySelector能定位的css选择器均可，比如：id、.class等
			up: {
				height: 30, //可选.默认50.触发上拉加载拖动距离
				auto: false, //可选,默认false.自动上拉加载一次
				contentrefresh: "正在加载...", //可选，正在加载状态时，上拉加载控件上显示的标题内容
				contentnomore: '没有更多数据了', //可选，请求完毕若没有更多数据时显示的提醒内容；
				callback: puful //必选，刷新函数，根据具体业务来编写，比如通过ajax从服务器获取新数据；
			}
		}
	});
	localStorage.removeItem('verifycode');
	localStorage.removeItem('dthxzverifycodeid');
	localStorage.removeItem('accesstoken');
	localStorage.removeItem('appkey');
	localStorage.removeItem('lng');
	localStorage.removeItem('lat');
	localStorage.removeItem('cstit');

	var ry = [];
	var sydwid = localStorage.getItem('compcode');
	//var sydwid = "Y10032503"; //模拟数据
	var slen = sydwid.length;
	sydwid = sydwid.substr(1, slen);
	sydwid='7'+sydwid;// 2019-01-15
	var record = 0; //返回值数组长度
	var req = {
		'req': 'getdtgz',
		'sydwid': sydwid,
		'pageno': 1,
		'pagesize': Dpage
	}
	//上拉加载刷新
	function puful() {
		req.pageno = parseInt(req.pageno) + 1; //页码
		//条数
		Request();
		console.log(record);
		if (record < req.pagesize) {
			this.endPullupToRefresh(true);

		} else {
			setTimeout(function() {
				mui('#refreshContainer').pullRefresh().enablePullupToRefresh();
				mui('#refreshContainer').pullRefresh().endPullupToRefresh();
			}, 1500)
		}

	}
	mui.ready(function() {
		//加载框
		mui.showLoading("正在加载..", ".warn-list");
		Request();
		//跳转地图页面
		mui('.fault-record-list').on('tap', '.fault-loc span', function() {
			var hxzid = $(this).parents('li').find('input.hxz').val(); // 黑匣子id
			var gzid = $(this).parents('li').attr('data-hxzgzid'); //黑匣子故障id
			var cstit = $(this).parents('li').find('.gz-tit').html(); //黑匣子故障id
			localStorage.setItem('cstit', cstit);
			console.log(cstit);
			gethxzinfo(hxzid, gzid);
			
			 var vhref = gethxzinfo(hxzid, gzid);
			if ('-999' == vhref) {
				mui.alert('提示：此故障无定位可查');
			} else {
				mui.openWindow({
					url: 'run-warn-map.html'
				})
			}
		});

		//跳转原生界面
		mui('.fault-record-list').on('tap', 'li a', function() {
			//$('.full-box').fadeIn();
			var hxzid = $(this).find('input.hxz').val(); // 黑匣子id
			var gzid = $(this).parent().attr('data-hxzgzid'); //黑匣子故障id

			// 2019-01-06 video修改成gzvideo,-999用来判断是否可以看视频

			var vhref = gethxzinfo(hxzid, gzid);
			if ('-999' == vhref) {
				mui.alert('提示：此故障无视频可查');
			} else {
				//播放视频条件        
				$(this).attr('href', vhref);
				//alert("要查看故障参数 " + $(this).attr('href'));
				window.location.href = this.href;
			}

			//故障维保人员信息
			var zcdm = $(this).find('input:last-child').val();
			//var zcdm = "3110-640104-201408-0074";
			var ry = ryRequest(zcdm);
			console.log(ry);
			for(var r=0; r<ry.length; r++){
				var ryone=ry[r];
				if(ryone.name.length>0){
					wbry = ryone.name;
					lxdh = ryone.mobile;
					break;e
				}
			}

			//故障电梯基本信息     
			gzlx = $(this).find('.fault-txt h4').html(); //故障类型
			dtsydd = $(this).find('input:first-child').val(); //故障发生地点
			dtnbbm = $(this).parent().attr('data-dtnbbm'); //故障内部编码
			//楼层 +  是否有人
			lc = $(this).find('.floor p span').html() + $(this).find('.floor h4 span').html();
			var kstime = $(this).find('.fault-im p').html(); //开始时间
			var thistime = getNowFormatDate(); //当前时间
			cxtime = timeCal(kstime, thistime); //持续时间
			console.log("cxtime = " + cxtime);
			getGZInfo(gzid); //故障基本信息方法调用
			console.log(getGZInfo(gzid));
		});
		//关闭原生界面
		mui('.full-close').on('tap', 'i', function() {
			$('.full-box').fadeOut();
		})
	});

	function Request() {
		var url = gzmain + "/lift/hxz5.jsp?req=getdtgz&wbdwid=" + req.sydwid + "&pageno=" + req.pageno + "&pagesize=" + req.pagesize;
		$.ajax(url, {
			//data: JSON.stringify(req),
			dataType: 'json', //服务器返回json格式数据
			type: 'post', //HTTP请求类型
			timeout: 20000, //超时时间
			async: true, //true异步加载
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
			},
			success: function(data) {
				if (data.code == 2001) {
					//返回值处理
					var ref = data.data;
					record = ref.length;
					console.log(data);
					var html = '';
					ref.forEach(function(v, i) {
						var theClass = '';
						var theInfo = '故障信息';
						var thePeo = '无人';

						var imgUrl = 'http://' + localStorage.getItem('ip') + ':' + localStorage.getItem('port') + '/lift/' + v.tplj;
						//var imgUrl = 'http://123.56.47.206:80/lift' + v.tplj;

						var fk_dthxzid = v.fk_dthxzid; //黑匣子ID

						if (v.sfyr != 0) {
							theClass = 'pink';
							theInfo = '困人信息';
							var thePeo = '有人';
						}
						html +=`
                        <li data-hxzgzid='${v.hxzgzid}' data-dtnbbm='${v.dtnbbm}' class="monbox">
                            <a>
                                <input type="hidden" value="${v.dtsydd}" />    
                                <h3 class="${theClass}">${theInfo}</h3>
                              <input type="hidden" class="hxz" value="${fk_dthxzid}"/>
                                <div class="mui-row">
                                    <div class="fault-im  mui-col-xs-4">
                                       <img src="${imgUrl}" src="${imgUrl}" data-preview-src="${imgUrl}"
                                        data-preview-group="${i}" />
                                        <p style='display:none;'>${v.gzkssj0}</p>
                                    </div>
                                    <div class="fault-txt  mui-col-xs-8">
                                       <h4 class='gz-tit'>${v.gzlx_chn}</h4>
                                        <div class="floor">
                                            <p class="mui-pull-left">楼层：<span>${v.lc} 层</span></p>
                                            <h4 class="mui-pull-right"><span>${thePeo}</span></h4>
                                        </div>
                                    </div>
                                </div>
                                <div class="nbbm fault-txt">
                                    <p>内部编码：<span>${v.dtnbbm}</span></p>
                                    <p>上报时间：${v.gzkssj0} </p>
                                </div>
                                <input type="hidden" value="${v.dtzcdm}" /> 
                            </a>
                            <div class="fault-loc">
						
                                <span></span>
                            </div>
                        </li>
                        `
					});
					$('.fault-record-list').append(html);

					//隐藏加载框
					mui.hideLoading(function() { //隐藏后的回调函数  
					});
				} else if (data.code == 2002) {
					/*mui.alert(data.msg, function() {
						mui.openWindow({
							url: '../../login.html'
						})
					});
					console.log(data);*/
				} else {
					/*console.log(data);
					mui.alert(data.msg, function() {
						mui.openWindow({
							url: '../../404.html'
						})
					});*/
				}
			},
			error: function(xhr, type, errorThrown) { //异常处理； console.log(type);
				/*alert('登录异常，请您重新登录');
				mui.openWindow({
					url: '../../login.html',
					id: 'login.html'
				})
				console.log(data);*/
			}
		});
	}
	//ajax 请求 黑匣子 视频播放信息 (黑匣子内信息 包含坐标)
	function gethxzinfo(fk_dthxzid, gzid) {
		var gzurl = gzmain + '/lift/hxz5.jsp?req=gethxzinfo&hxzid=' + fk_dthxzid;
		var verifycode = ''; //视频观看code
		var deviceserial = '';
		var accesstoken = '';
		var appkey = '';
		var lng = '';
		var lat = '';
		$.ajax(gzurl, {
			dataType: 'json', //服务器返回json格式数据
			timeout: 20000, //超时时间
			async: false, //true异步加载
			success: function(data) {
				if (data.code == 2001) {
					//返回值处理
					console.log(data);
					var ref = data.data;
					verifycode = ref[0].verifycode; //视频观看code
					deviceserial = ref[0].deviceserial;
					accesstoken = ref[0].accesstoken;
					appkey = ref[0].appkey;
					lng = ref[0].lng;
					lat = ref[0].lat;
					console.log(ref);
					localStorage.setItem('verifycode', verifycode);
					localStorage.setItem('deviceserial', deviceserial);
					localStorage.setItem('accesstoken', accesstoken);
					localStorage.setItem('appkey', appkey);
					localStorage.setItem('lng', lng);
					localStorage.setItem('lat', lat);

				} else if (data.code == 2002) {
					/*mui.alert(data.msg, function() {
						mui.openWindow({
							url: '../../login.html'
						})
					});
					console.log(data)*/
				} else {
					/*console.log(data);
					mui.alert(data.msg, function() {
						mui.openWindow({
							url: '../../404.html'
						})
					});*/
				}
			},
			error: function(xhr, type, errorThrown) { //异常处理； console.log(type);
				/*alert('登录异常，请您重新登录');
				mui.openWindow({
					url: '../../login.html',
					id: 'login.html'
				})
				console.log(data);*/
			}
		});
		if (accesstoken != '' && deviceserial != '' && verifycode != '' && appkey != '') {
			return "dt:req=gzvideo;at=" + accesstoken + ";deviceSerial=" + deviceserial + ";verifyCode=" + verifycode +";gzid=" + gzid + ";appkey=" + appkey;
		} else {
			return "-999";
		}
	}
	//请求维保人员信息
	function ryRequest(zcdm) {
		var url = domain + "/dtwbgl/dtdesc.h5";
		var ryreq = {
			'dtcode': zcdm,
			'userid': localStorage.getItem('userid'),
			'token': localStorage.getItem('token')
		}

		$.ajax(url, {
			//data: JSON.stringify(ryreq),
			data: ryreq,
			dataType: 'json', //服务器返回json格式数据
			type: 'post', //HTTP请求类型
			timeout: 30000, //超时时间
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
			},
			async: false, //true异步加载
			success: function(data) {
				if (data.code == 2001) {
					console.log(data);
					// 维保人员
					var ref = data.data;
					if (JSON.stringify(ref) != "{}") {
						ry = ref.ry;
					}
				} else if (data.code == 2002) {
					alert('登录异常，请您重新登录');
					mui.openWindow({
						url: '../../login.html',
						id: 'login.html'
					})
					console.log(data);
				} else {
					mui.openWindow({
						url: '../../404.html',
						id: '404.html'
					})
				}
			},
			error: function(xhr, type, errorThrown) { //异常处理； console.log(type);
				alert('登录异常，请您重新登录');
				mui.openWindow({
					url: '../../login.html',
					id: 'login.html'
				})
			}
		});
		return ry;
	}

	//时间计算
	function timeCal(time1, time2) {
		var date1 = new Date(time1.replace(/-/g, "/"))
		var date2 = new Date(time2.replace(/-/g, "/"))
		// 2019-01-19
		//var date1 = new Date(time1)
		//var date2 = new Date(time2)
		var s1 = date1.getTime();
		var	s2 = date2.getTime();
		var total = (s2 - s1) / 1000;
		var day = parseInt(total / (24 * 60 * 60)); //计算整数天数
		var afterDay = total - day * 24 * 60 * 60; //取得算出天数后剩余的秒数
		var hour = parseInt(afterDay / (60 * 60)); //计算整数小时数
		var afterHour = total - day * 24 * 60 * 60 - hour * 60 * 60; //取得算出小时数后剩余的秒数
		var min = parseInt(afterHour / 60); //计算整数分
		var afterMin = parseInt(total - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60); //取得算出分后剩余的秒数
		return day + "天" + hour + "时" + min + "分" + afterMin + "秒";
	}
	//排序
	function compare(property) {
		return function(a, b) {
			var value1 = a[property];
			var value2 = b[property];
			return value1 - value2;
		}
	}

})
